package com.example.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.server.bean.Menu;
import com.example.server.bean.MenuRole;
import com.example.server.util.RespBean;
import com.example.server.bean.Role;
import com.example.server.service.IMenuRoleService;
import com.example.server.service.IMenuService;
import com.example.server.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ProjectName: yeb
 * Author: 别怿言
 * Date: 2023-02-06 21:53
 * Description：角色相关基本信息接口
 */
@Api(tags = "PermissionManager")
@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IMenuRoleService menuRoleService;

    @ApiOperation(value = "查询所有角色")
    @GetMapping("/")
    public RespBean getPermissions() {
        List<Role> roles = roleService.list();
        return RespBean.success("查询成功！", roles);
    }

    @ApiOperation(value = "新增角色")
    @PostMapping("/role")
    public RespBean addPermission(@RequestBody Role role) {
        String rolename = role.getName();
        if (!rolename.startsWith("ROLE_")) {
            role.setName("ROLE_" + rolename);
        }
        if (roleService.save(role)) {
            return RespBean.success("新增成功！");
        }
        return RespBean.error("新增失败！");
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{rid}")
    public RespBean deletePermission(@PathVariable Integer rid) {
        if (roleService.removeById(rid)) {
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }

    @ApiOperation(value = "查询菜单列表")
    @GetMapping("/menus")
    public List<Menu> getAllMenus() {
        return menuService.getAllMenus();
    }

    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMenusByRole(@PathVariable Integer rid) {
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",rid))
                .stream().map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    public RespBean updateMenuRole(Integer rid,Integer[] mids) {
        return menuRoleService.updateMenuRole(rid,mids);
    }
}
